package com.norra.client.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.norra.base.api.ApiCallback
import com.norra.base.api.HError
import com.norra.base.api.WebService
import com.norra.base.api.entity.BaseResponse
import com.norra.base.api.entity.LoginRequest
import com.norra.base.api.entity.LoginToken
import com.norra.base.viewmodel.NetworkResource

class LoginViewModel : ViewModel() {

    fun getVerifyCode(phone:String) : LiveData<NetworkResource<Boolean>> {
        val result = MutableLiveData<NetworkResource<Boolean>>()
        val map = HashMap<String, String>()
        map["username"] = phone
        map["phone"] = phone
        WebService.get().getVerifyCode(map).enqueue(object : ApiCallback<BaseResponse>{
            override fun onSuccess(response: BaseResponse) {
                result.postValue(NetworkResource.success(true))
            }

            override fun onError(error: HError) {
                result.postValue(NetworkResource.error(error))
            }

        })
        return result
    }

    fun login(phone:String, code:String) : LiveData<NetworkResource<LoginToken>> {
        val result = MutableLiveData<NetworkResource<LoginToken>>()
        val request = LoginRequest()
        request.username = phone
        request.pwd = code
        WebService.get().login(request).enqueue(object : ApiCallback<LoginToken>{
            override fun onSuccess(response: LoginToken) {
                result.postValue(NetworkResource.success(response))
            }

            override fun onError(error: HError) {
                result.postValue(NetworkResource.error(error))
            }

        })
        return result
    }
}